package com.tansun.easycare.rule.ruleversion.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tansun.easycare.core.config.Global;
import com.tansun.easycare.core.service.impl.CrudServiceImpl;
import com.tansun.easycare.rule.common.model.VersionModel;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.rulegroup.entity.RuleGroup;
import com.tansun.easycare.rule.rulegroup.service.RuleGroupService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleversion.dao.RuleVersioninfoDao;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.rule.utils.StringUtils;

@Service("ruleVersioninfoService")
public class RuleVersioninfoServiceImpl extends CrudServiceImpl<RuleVersioninfoDao, RuleVersioninfo> implements RuleVersioninfoService {
    
	@Autowired
    private RuleManageService ruleManageService;
    @Autowired
    private RuleGroupService ruleGroupService;

    public List<RuleVersioninfo> findVersionList(Map<String, Object> map) {
        return this.dao.findVersionList(map);
    }

    public List<VersionModel> findVersionModelList(Map<String, Object> map) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        List<RuleVersioninfo> list = this.findVersionList(map);
        List<VersionModel> verList = new ArrayList<VersionModel>();
        for (RuleVersioninfo ruleVersion : list) {
            if (ruleVersion.getVersion() != null && ruleVersion.getVersion().matches("tmp")) {
                continue;
            }
            VersionModel ver = new VersionModel();
            ver.setManageId(ruleVersion.getManageId());
            ver.setProjectCode(ruleVersion.getProjectCode());
            ver.setModelType(ruleVersion.getModelType());
            ver.setVersion(ruleVersion.getVersion());
            ver.setModifiedTime(sdf.format(ruleVersion.getCreateDate()));
            ver.setOrderSeq(Double.valueOf(ruleVersion.getVersion().substring(1)));
            verList.add(ver);
        }
		Collections.sort(verList, new Comparator(){
				@Override
				public int compare(Object o1, Object o2) {
					VersionModel stu1=(VersionModel)o1;
					VersionModel stu2=(VersionModel)o2;
					return stu1.getOrderSeq().compareTo(stu2.getOrderSeq());
				}	    	
		    });
        Collections.reverse(verList);
        return verList;
    }
    
    public List<VersionModel> findVersionModelList(String projectCode,String modelType,String code) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		RuleManage rm = ruleManageService.findByCode(code, projectCode);
		
		RuleGroup ruleGroup = new RuleGroup();
		ruleGroup.setProjectCode(projectCode);
		ruleGroup.setManageId(rm.getId());
		List<RuleGroup> rglist = ruleGroupService.findList(ruleGroup);
		List<VersionModel> verList = new ArrayList<VersionModel>();
		for(int i =0;i<rglist.size();i++) {
			RuleGroup rg = rglist.get(i);
			VersionModel vm = new VersionModel();
			vm.setManageId(rm.getId());
			vm.setVersion(rg.getVersion());
			vm.setModelType(modelType);
			vm.setModifiedTime(sdf.format(rg.getUpdateDate()));
			vm.setProjectCode(projectCode);
			Double seq = Double.parseDouble(rg.getVersion().replaceAll("v", ""));
			vm.setOrderSeq(seq);
			verList.add(vm);
		}
		Collections.sort(verList, new Comparator(){
			@Override
			public int compare(Object o1, Object o2) {
				VersionModel stu1=(VersionModel)o1;
				VersionModel stu2=(VersionModel)o2;
				return stu1.getOrderSeq().compareTo(stu2.getOrderSeq());
			}
		});
	    Collections.reverse(verList);
	    return verList;
    }

    /**
     * 查找已发布的规则项目
     */
    public List<RuleVersioninfo> findPublishRuleList(String projectCode) {
        return this.dao.findPublishRuleList(projectCode);
    }

    /**
     * 获取更新规则集（用于规则流分支之前） 如没有这条记录就添加一条
     */
    public RuleVersioninfo getEmptyRuelSet() throws Exception {
        RuleVersioninfo emptyRule = null;
        RuleVersioninfo queryVersion = new RuleVersioninfo();
        queryVersion.setModelType("EMPTYRULE");
        List<RuleVersioninfo> results = this.dao.findList(queryVersion);
        if (results.size() == 0) {
            emptyRule = new RuleVersioninfo();
            String ruleName = StringUtils.generateShortUuid();
            String ruleFlowGroup = "emptysetforupdate";
            String ruleContent = "package com.tansun.ruleGroup \n"
                    + "import java.util.*; \n"
                    + "import com.tansun.rule.utils.*; \n"
                    + "global RuleHelper ruleHelper; \n"
                    + "global DroolsRuleLog droolsRuleLog; \n"
                    + "global java.util.Map metaMap; \n"
                    + "global java.util.Map dataMap; \n"
                    + "dialect \"mvel\" \n"
                    + "ruleflow-group \"" + ruleFlowGroup + "\" \n"
                    + "rule updateInsertMap_" + ruleName +"\n"
                    + "salience 2147483647 \n"
                    + "no-loop \n"
                    + "true \n"
                    + "when \n"
                    + "$insertMap : Map() \n"
                    + "then  \n"
                    + "update($insertMap); \n"
                    + "end \n";
            emptyRule.setRuleContent(ruleContent);
            emptyRule.setModelType("EMPTYRULE");
            emptyRule.setProjectCode("rule");
            emptyRule.setVersion("v0.00empty");
            emptyRule.setManageId(ruleFlowGroup);
            this.save(emptyRule);
        } else {
            emptyRule = results.get(0);
        }
        return emptyRule;
    }

    /**
     * 更新规则信息（在发布的时候讲 code+version更新成发布后最新的内容）
     */
    public void updateRuleContent(RuleManage ruleManage) throws BizException {
        RuleVersioninfo verCon = new RuleVersioninfo();
        verCon.setManageId(ruleManage.getId());
        verCon.setVersion(ruleManage.getOldVersion());
        List<RuleVersioninfo> verList = this.findList(verCon);
        if (verList == null || verList.size() == 0) {
            throw new BizException("E-100001");
        }
        RuleVersioninfo verInfo = verList.get(0);
        verInfo.setId(null);
        verInfo.setVersion(ruleManage.getVersion());
        try {
            String ruleContent = verInfo.getRuleContent();
            ruleContent = ruleContent.replaceAll(ruleManage.getCode() + ruleManage.getOldVersion(), ruleManage.getCode() + ruleManage.getVersion());
            ruleContent = ruleContent.replaceAll(ruleManage.getCode() + "_" + ruleManage.getOldVersion(), ruleManage.getCode() + "_" + ruleManage.getVersion());
            //verInfo.setHbRuleContent(ruleContent);
            verInfo.setRuleContent(ruleContent);
            this.save(verInfo);
        } catch (Exception e) {
            throw new BizException(e, "E-000500");
        }
    }
    
    /**
     * 更新规则信息（更新成发布后最新的内容）
     */
    public void update(RuleVersioninfo ruleVersioninfo) throws BizException {
        try {
        	this.dao.update(ruleVersioninfo);
        } catch (Exception e) {
            throw new BizException(e, "E-000500");
        }
    }

    @Override
    public List<RuleVersioninfo> findPublishVersionList(RuleVersioninfo info) throws BizException {
        return this.dao.findPublishVersionList(info);

    }




	 @Override
	 public  List<RuleVersioninfo> findCurrVerList(RuleVersioninfo  info) throws BizException{
		 return  this.dao.findCurrVerList(info);
		 
	 }
		@Override
		public List<RuleVersioninfo> findChallengerInfo(Map<String, Object> map) {
			return  this.dao.findChallengerInfo(map);
		}

		@Override

		public List<RuleVersioninfo> findRuleRefeVersion(Map<String, Object> map) {
			// TODO Auto-generated method stub
			return this.dao.findRuleRefeVersion(map);
		}

		@Override
		public List<String> findRuleRefeCodes(Map<String, String> map) {
			// TODO Auto-generated method stub
			return  this.dao.findRuleRefeCodes(map);
		}
		public void updateIsValid(RuleVersioninfo ruleVersioninfo) {
			  this.dao.updateIsValid(ruleVersioninfo);
			

		}
	 
		public Map<String,String>  findRuleRefeVerMap(String  projectCode){
			Map<String,String> retMap  = new  HashMap<>();
    	    Map<String,String>  varMap  = new  HashMap<String,String>();
       	    varMap.put("projectCode", projectCode);
    	    List<String> codesList = this.findRuleRefeCodes(varMap);
    	    
            if (codesList !=null && codesList.size() >0) {
               Map<String,Object>  vrMap = new  HashMap<String,Object>();
               vrMap.put("projectCode", projectCode);
               vrMap.put("refeList", codesList);
               List<RuleVersioninfo> verList=this.findRuleRefeVersion(vrMap);
               for (RuleVersioninfo ruleVer:verList) {
            	   retMap.put(ruleVer.getModelCode(), ruleVer.getRuleContent());
               }
            }
            return  retMap;
		}

		@Override
		public Map<String,String> findProjectRefeVersion(String projectCode) {
			Map<String,String>  varMap  = new  HashMap<>();
			varMap.put("projectCode", projectCode);
			Map<String,String> retMap  = new  HashMap<>();
			List<RuleVersioninfo> verList=  this.dao.findProjectRefeVersion(varMap);
            for (RuleVersioninfo ruleVer:verList) {
         	   retMap.put(ruleVer.getModelCode(), ruleVer.getRuleContent());
            }
			return retMap;
		}
		public List<RuleVersioninfo> findProjectRefeList(String projectCode) {
			Map<String,String>  varMap  = new  HashMap<>();
			varMap.put("projectCode", projectCode);
			List<RuleVersioninfo> verList=  this.dao.findProjectRefeVersion(varMap);
			return verList;
		}
		
		@Override
		public List<RuleVersioninfo> findNewPublishVersionList(RuleVersioninfo info) throws BizException {
			// TODO Auto-generated method stub
			return this.dao.findNewPublishVersionList(info);
		}
		@Override
		public void deleteByMutilVersion(RuleManage ruleManage, List<String> versions){
			if(versions!=null&&versions.size()>0) {
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("projectCode", ruleManage.getProjectCode());
				map.put("manageId", ruleManage.getId());
				map.put("type", ruleManage.getModelType());
				map.put("versions", versions);
				this.dao.deleteByMutilVersion(map);
			}
		}

		public void updateAntoApprove(RuleVersioninfo ruleVersioninfo) {
			String  isapprove =Global.getConfig("version.isapprove");
			if (!StringUtils.isEmpty(isapprove)) {
				if ("0".equals(isapprove)) {
					if (!"1".equals(ruleVersioninfo.getIsValid())) {
						ruleVersioninfo.setIsValid("1");
					}
				}
			}
		}
		
		@Override
		public void save(RuleVersioninfo ruleVersioninfo) {
			this.updateAntoApprove(ruleVersioninfo);
			super.save(ruleVersioninfo);
		}
}
